package sg.edu.nus.comp.icreate.ivletalk;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import sg.edu.nus.comp.icreate.ivletalk.module.MainActivity;
import sg.edu.nus.comp.icreate.ivletalk.utils.net.DataPuller;
import sg.edu.nus.comp.icreate.ivletalk.utils.xml.UserValidateXmlParser;
import android.content.Context;
import android.util.Log;

public class User {
	public static final String USER_FILENAME = "user";
	private String token;
	private static User user;

	public static User createInstance(FileInputStream file) throws IOException {
		user = new User(file);
		file.close();
		return user;
	}

	public String getToken() {
		return token;
	}

	public static User createInstance(Context context, String token) {
		user = new User(token);
		FileOutputStream fos;
		try {
			fos = context.openFileOutput(USER_FILENAME, Context.MODE_PRIVATE);
			fos.write(token.getBytes());
			fos.close();
		} catch (Exception e) {
			Log.e("err", "Cannot write to file", e);
		}
		return user;
	}

	private User(FileInputStream file) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(file));
		token = reader.readLine();
	}

	private User(String token) {
		this.token = token;
	}

	public static User getInstance() {
		return user;
	}

	public static boolean isValid() {
		if (user == null)
			return false;
		try {
			String url = "https://ivle.nus.edu.sg/api/Lapi.svc/Validate?APIKey=" + MainActivity.APIKEY + "&Token=" + user.token + "&output=xml";
			return (Boolean) (new DataPuller(new UserValidateXmlParser()).execute(url).get());
		} catch (Exception e) {
			Log.e("error", "Error in check auth validity", e);
			return false;
		}
	}

	public static void clearUserPersistence(Context context) {
		try {
			context.deleteFile(USER_FILENAME);
		} catch (Exception e) {
			Log.e("err", "Cannot delete file", e);
		}
	}
}
